/*******************************************************************************
 * Copyright 2017 Bstek
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.  You may obtain a copy
 * of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
package com.bstek.urule.runtime.builtinaction;

import com.bstek.urule.Utils;
import com.bstek.urule.model.library.action.annotation.ActionBean;
import com.bstek.urule.model.library.action.annotation.ActionMethod;
import com.bstek.urule.model.library.action.annotation.ActionMethodParameter;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jacky.gao
 * @since 2016年6月21日
 */
@Component("urule.objectAction")
@ActionBean(name="对象")
public class ObjectAction {

	@ActionMethod(name="对象转换成Map")
	@ActionMethodParameter(names={"对象"})
	public Map<String,Object> objectToMap(Object obj){
		Map<String,Object> objectMap = new HashMap<>();
		Class<?> clazz = obj.getClass();
		try {
			for (Field field : clazz.getDeclaredFields()) {
				field.setAccessible(true);
				Object value = field.get(obj);
				objectMap.put(field.getName(), value);
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return objectMap;
	}

	@ActionMethod(name="对象取属性值")
	@ActionMethodParameter(names={"对象","属性值"})
	public Object value4Obj(Object obj, String propertyName){
		return Utils.getObjectProperty(obj, propertyName);
	}
}
